﻿using ManYan.Domain.DomainService;
using ManYan.Domain.Model.Entity;
using ManYan.Repository.Interfaces;
using Org.BouncyCastle.Utilities.Encoders;
using System.ComponentModel;

namespace ManYan.Infrastructure.DomainService
{
    public class WechatUserDomainService : IWechatUserDomainService
    {
        public readonly IBaseRepository<WechatUser> _baseRepository;

        public readonly IBaseRepository<tb_user_refresh_token> _tokenRepository;
        public WechatUserDomainService(IBaseRepository<WechatUser> baseRepository, IBaseRepository<tb_user_refresh_token> tokenRepository)
        {
            _baseRepository = baseRepository;
            _tokenRepository = tokenRepository;
        }
        public WechatUser WhereLoadEntity(System.Linq.Expressions.Expression<Func<WechatUser, bool>> expression)
        {

            WechatUser user = new WechatUser();
            user.OpenId = "";
            user.NickName = "";
            user.Avatar = "";
            user.Sex = "";
            _baseRepository.AddEntity(user);//添加实体
            return _baseRepository.WhereLoadEntity(expression);
        }
        public WechatUser WechatUserAdd(string OpenId, string NickName, string Avatar, string Sex)
        {
            WechatUser user = _baseRepository.WhereLoadEntity(x => x.OpenId == OpenId);
            if (user != null)//表示当前用户已经存在
                return user;
            _baseRepository.BeginTran();//开始事务
            try
            {
                user = new WechatUser();
                user.OpenId = OpenId;
                user.NickName = NickName;
                user.Avatar = Avatar;
                user.Sex = Sex;
                _baseRepository.AddEntity(user);//添加实体

                tb_user_refresh_token token = new tb_user_refresh_token();
                token.UserId = user.Id;
                token.Token = "";
                _tokenRepository.AddEntity(token);
               

                _baseRepository.Commit();//提交（保存实体，提交事务）

            }
            catch
            {
                _baseRepository.RollbackTran();//回滚
            }
            user = _baseRepository.WhereLoadEntity(x => x.OpenId == OpenId);
            return user;
        }
    }
}